package org.bite.lesson11;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class Demo1101 {
    public static void main(String[] args) {
        //实现Callable接口，定义任务
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws InterruptedException {
                System.out.println("执行运算");
                int sum = 0;
                for(int i = 1; i <= 1000; i++){
                    sum+=i;
                }
                TimeUnit.SECONDS.sleep(1);
                throw new InterruptedException("执行过程中出现了异常...");
//                System.out.println("执行完成");
//                return sum;
            }
        };

        //Callable要配合FutureTask一起使用，FutureTask用来获取Callable的执行效果
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        //FutureTask当作构造参数传入Thread构造方法中
        Thread thread = new Thread(futureTask);
        thread.start();
        try{
            // 等待结果的时间可能被中断，会抛出InterruptedException
            Integer result = futureTask.get();
            System.out.println("结果是：" + result);
        }catch(InterruptedException e){
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
            // 打印异常信息
            System.out.println("打印日志：" + e.getMessage());
        }
    }
}
